from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, JSONResponse
import uvicorn
from calibration import CameraCalibrator
from camera_tracker import CameraTracker
#仅测试
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()

# 允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局变量（实际应用中应使用更安全的方式）
RTSP_URL = "rtsp://admin:Admin123@192.168.88.97:554/Streaming/Channels/101"
tracker = CameraTracker(RTSP_URL)

# 设置模板目录
templates = Jinja2Templates(directory="templates")

# 主页路由
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse(
        "index.html",
        {"request": request, "title": "FastAPI网页", "message": "欢迎来到我的FastAPI网页!"}
    )

@app.post("/calibrate")
def calibrate_camera():
    """执行相机标定"""
    calibrator = CameraCalibrator(RTSP_URL)
    result = calibrator.calibrate()
    return result

@app.post("/start-tracking")
def start_tracking():
    """启动人员跟踪"""
    return tracker.start_tracking()

@app.post("/stop-tracking")
def stop_tracking():
    """停止人员跟踪"""
    return tracker.stop_tracking()

@app.get("/tracking-data")
def get_tracking_data():
    """获取最新的跟踪数据"""
    data = tracker.get_latest_data()
    return JSONResponse(content={
        "positions": data["positions"],
        "frame": data["frame"] and data["frame"].hex(),  # 转换为十六进制字符串
        "map": data["map"] and data["map"].hex()
    })

@app.get("/video-feed")
def video_feed():
    """视频流端点"""
    def generate():
        while True:
            data = tracker.get_latest_data()
            if data["frame"]:
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + data["frame"] + b'\r\n')
    
    return StreamingResponse(
        generate(),
        media_type="multipart/x-mixed-replace;boundary=frame"
    )

@app.get("/map-feed")
def map_feed():
    """平面图流端点"""
    def generate():
        while True:
            data = tracker.get_latest_data()
            if data["map"]:
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + data["map"] + b'\r\n')
    
    return StreamingResponse(
        generate(),
        media_type="multipart/x-mixed-replace;boundary=frame"
    )

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)